/* jslint unused: false */
/* global define, $, console, alert */
define(function(require) {

    'use strict';

    var _ = require('underscore'),
        Backbone = require('backbone'),
        Base = require('components/pop/base'),
        tpl = require('text!components/pop/templates/chosen.html'),
        Utils = require('core/utils'),
        select2 = require('select2');

    return Base.extend({

        template: _.template(tpl),

        className: 'popover bottom popover-chosen-wrap',

        events: {
            'click .js-btn-cancel': 'hide',
            'click .js-btn-confirm': 'triggerCallback'
        },

        initialize: function(options) {
            var view = this;

            Base.prototype.initialize.call(view, options);
            window.NC.on('chosen:hide', function() {
                view.hide();
            });
            view.data = options.data;
        },

        render: function() {
            var view = this;

            view.$el.html(view.template({}));

            return view;
        },

        reset: function(obj) {
            var view = this;

            var callback = obj.callback,
                target = obj.target,
                trigger = obj.trigger,
                data = obj.data;

            view.setCallback(callback);
            view.setTarget(target);
            view.setTrigger(trigger);
            view.setData(data);
            view.positioning();
            view.show();
        },

        positioning: function() {
            var view = this;

            view.$el.show().position({
                of: view.target,
                my: 'center top+5',
                at: 'center bottom',
                collision: 'none'
            });

            view.initSkuList();

            var tags = view.getSelect2Tags();

            view.openSelect2(tags);
        },

        getSelect2Tags: function() {
            var view = this;

            var dataArr = view._skuList[view.data.id],
                tags;

            if (!_.isUndefined(dataArr) && dataArr.length > 0) {
                tags = dataArr;
            } else {
                tags = [];
            }

            return tags;
        },

        initSkuList: function() {
            var view = this;

            view._skuList = {};
            _.each(window._global.skuTree, function(item, index) {
                var arr = [];
                _.each(item.list, function(atom) {
                    arr.push({
                        id: atom._id,
                        text: atom.text
                    });
                });
                view._skuList[item._id] = arr;
            });
        },

        openSelect2: function(tags) {
            var view = this;

            view._selectedData = [];
            view.$('.js-select2').off('select2-selecting change').select2({
                allowClear: true,
                multiple: true,
                placeholder: '添加规格值',
                // selectOnBlur: true,
                tags: tags,
                maximumInputLength: 20,
            }).on('select2-selecting', function(event) {
                view.onSelect2Selecting(event);
            }).on('change', function(event) {
                view.onSelect2Change(event);
            }).select2('open');
        },

        onSelect2Selecting: function(event) {
            var view = this;

            var data = event.object,
                ele = $(event.target);

            if (data.id !== -1 && !(_.isString(data.id) && data.id === data.text)) {
                view._selectedData.push(data);
            } else {
                var url;

                if (Utils.isFenxiao()) {
                    url = window._global.url.fenxiao + '/showcase/WCGoodsSkuTree/skuLeaf.json';
                } else {
                    url = window._global.url.www + '/showcase/WCGoodsSkuTree/skuLeaf.json';
                }
                $.post(url, {
                    text: data.text,
                    _id: view.data.id
                }, function(resp) {
                    if (resp.code === 0) {
                        var result = {
                            id: Number(resp.data),
                            text: data.text
                        };
                        var skuTree = _.find(window._global.skuTree, function(sku) {
                            return sku._id === view.data.id
                        });
                        if(skuTree) {
                            if(!skuTree.list) {
                                skuTree.list = []
                            }
                            skuTree.list.push({
                                _id: result.id,
                                text: result.text
                            });
                        }
                        // @todo 删除相同 id 的数据。
                        view._selectedData.push(result);
                        ele.select2('data', view._selectedData);
                        ele.select2('close');
                    } else {
                        Utils.errorNotify(resp.msg || '出错啦。');
                    }
                }, 'json');

                event.preventDefault();
            }
        },

        onSelect2Change: function(event) {
            var view = this;

            if (event.removed) {
                var item = _.find(view._selectedData, function(item) {
                    return item.id === event.removed.id;
                });
                view._selectedData.splice(view._selectedData.indexOf(item), 1);
            }
        },

        clearInput: function() {
            var view = this;

            view.txt.val('');
        },

        setData: function(data) {
            var view = this;

            view.data = data;
        },

        hide: function() {
            var view = this;

            view.$('.js-select2').select2('data', '').select2('destroy');
            view._selectedData = [];
            view.$el.hide();

            return view.$el;
        },

        triggerCallback: function() {
            var view = this;

            view.callback(view._selectedData);
            view.hide();
        }
    });
});
